package com.yssystem.interceptor;



import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Component
@RequiredArgsConstructor
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private  RedisTemplate<String,String> redisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("发送了请求");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String token = request.getHeader("Authorization");
        try {
            String redisToken = redisTemplate.opsForValue().get(token);
            if (redisToken ==null) {
                throw new RuntimeException();
            }
            return  true;
        } catch (Exception e) {
            response.setStatus(401);
            throw new RuntimeException(e);
        }
    }
}
